package bb.lanxing.mvp.presetner;

import bb.lanxing.model.WorkoutDatabaseHelper;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.mvp.model.HistoryModelImpl;
import bb.lanxing.mvp.model.i.IHistoryModel;
import bb.lanxing.mvp.presetner.i.IWorkoutMergeListPresenter;
import bb.lanxing.mvp.view.i.IWorkoutMergeListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class WorkoutMergeListPresenterImpl extends BasePresenter implements IWorkoutMergeListPresenter {
    private Subscription downloadSubscription;
    private int index;
    private int total;
    private IWorkoutMergeListView view;
    private long[] workoutIds;
    private IHistoryModel model = new HistoryModelImpl();
    private List<Workout> workouts = new ArrayList();

    public WorkoutMergeListPresenterImpl(long[] vWorkoutIds, IWorkoutMergeListView mergeView) {
        view = mergeView;
        workoutIds = vWorkoutIds;
        if (workoutIds.length > 0) {
            workoutSort(workoutIds);
        }
    }

    private void workoutSort(long[] vWorkoutIds) {
        for (long j : vWorkoutIds) {
            workouts.add(Workout.getById(j));
        }
        Collections.sort(workouts, new Comparator<Workout>() {
            @Override
            public int compare(Workout o1, Workout o2) {
                if (o1.getStartTime() - o2.getStartTime() == 0) {
                    return 0;
                }
                return o1.getStartTime() - o2.getStartTime() > 0 ? 1 : -1;
            }
        });
        for (int i = 0; i < workouts.size(); i++) {
            vWorkoutIds[i] = workouts.get(i).getId();
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        view = null;
        downloadSubscription = null;
        workouts.clear();
    }

    @Override
    public int getItemCount() {
        long[] jArr = workoutIds;
        if (jArr != null) {
            return jArr.length;
        }
        return 0;
    }

    @Override
    public Workout getItem(int position) {
        if (position < 0 || position >= workoutIds.length) {
            return null;
        }
        return workouts.get(position);
    }

    @Override
    public void move(int from, int to) {
        long[] jArr = workoutIds;
        long j = jArr[from];
        jArr[from] = jArr[to];
        jArr[to] = j;
    }

    @Override
    public long[] getWorkoutIds() {
        return workoutIds;
    }

    @Override
    public boolean isDownloading() {
        Subscription subscription = downloadSubscription;
        return (subscription == null || subscription.isUnsubscribed()) ? false : true;
    }

    @Override
    public boolean isDownloaded() {
        for (long j : workoutIds) {
            if (!model.isDownloaded(Workout.getById(j))) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void download() {
        if (isDownloading()) {
            return;
        }
        int length = workoutIds.length;
        Long[] lArr = new Long[length];
        int i = 0;
        while (true) {
            long[] jArr = workoutIds;
            if (i < jArr.length) {
                lArr[i] = jArr[i];
                i++;
            } else {
                total = length;
                index = 1;
                view.onDownloadStarted();
                view.onProgressUpdate(index, total);
                Subscription subscribe = Observable.from(lArr).subscribeOn(Schedulers.io()).map(new Func1<Long, Workout>() {
                    @Override
                    public Workout call(Long aLong) {
                        return Workout.getById(aLong);
                    }
                }).flatMap(new Func1<Workout, Observable<Workout>>() {
                    @Override
                    public Observable<Workout> call(Workout workout) {
                        return downloadWorkoutIfNeed(workout);
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        if (view == null || isUnsubscribed()) {
                            return;
                        }
                        view.onDownloadCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (view == null || isUnsubscribed()) {
                            return;
                        }
                        view.onDownloadFailed();
                    }

                    @Override
                    public void onNext(Workout workout) {
                        if (view == null || isUnsubscribed() || index >= total) {
                            return;
                        }
                        index++;
                        view.onProgressUpdate(index, total);
                    }
                });
                downloadSubscription = subscribe;
                addSubscription(subscribe);
                return;
            }
        }
    }

    public Observable<Workout> downloadWorkoutIfNeed(final Workout workout) {
        return Observable.just(workout).flatMap(new Func1<Workout, Observable<Workout>>() {
            @Override
            public Observable<Workout> call(final Workout workout2) {
                if (model.isDownloaded(workout2)) {
                    return Observable.just(workout2);
                }
                return model.requestWorkoutDetail(workout2).flatMap(new Func1<Workout, Observable<List<Trackpoint>>>() {
                    @Override
                    public Observable<List<Trackpoint>> call(Workout workout3) {
                        return model.requestWorkoutPoint(workout3);
                    }
                }).map(new Func1<List<Trackpoint>, Workout>() {
                    @Override
                    public Workout call(List<Trackpoint> trackpoints) {
                        Workout queryWorkoutById = WorkoutDatabaseHelper.queryWorkoutById(workout2.getId());
                        if (queryWorkoutById == null) {
                            return workout2;
                        }
                        queryWorkoutById.setPointCounts(trackpoints.size());
                        WorkoutDatabaseHelper.save(queryWorkoutById);
                        return queryWorkoutById;
                    }
                });
            }
        });
    }
}
